export const PlatformAdapter = {
  async request<T>(method: string, url: string, data?: any, headers: Record<string, string> = {}): Promise<T> {
    if (typeof wx !== 'undefined' && wx.request) {
      return new Promise((resolve, reject) => {
        wx.request({
          url,
          method,
          data,
          header: headers,
          success: res => resolve(res.data),
          fail: err => reject(err)
        });
      });
    } else {
      try {
        // 自动拼 GET 参数
        if (method === 'GET' && data) {
          const query = this.objectToQueryString(data);
          if (query) url += (url.includes('?') ? '&' : '?') + query;
        }

        const res = await fetch(url, {
          method,
          headers: {
            'Content-Type': 'application/json',
            ...headers
          },
          body: method === 'GET' ? null : JSON.stringify(data)
        });

        if (!res.ok) {
          const text = await res.text();
          console.error("FETCH FAILED:", res.status, text);
          throw new Error(`Network error: ${res.status}`);
        }

        return await res.json();
      } catch (err) {
        console.error("FETCH ERROR:", err);
        throw new Error('Fetch exception');
      }
    }
  },

  /**
   * 将对象转换为查询字符串
   * @param obj - 需要转换的对象
   * @returns 格式化后的查询字符串
   */
  objectToQueryString(obj: Record<string, any>): string {
    if (!obj || typeof obj !== 'object') return '';
    
    return Object.keys(obj)
      .filter(key => obj[key] != null) // 过滤掉 null 和 undefined 值
      .map(key => {
        const value = obj[key];
        const encodedKey = encodeURIComponent(key);
        
        if (Array.isArray(value)) {
          // 处理数组参数
          return value
            .map(item => `${encodedKey}=${encodeURIComponent(String(item))}`)
            .join('&');
        }
        
        return `${encodedKey}=${encodeURIComponent(String(value))}`;
      })
      .join('&');
  }
};
